﻿// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if !NET40
using System;
using System.Threading.Tasks;

namespace CuteAnt.IO.Pipelines
{
  internal static class PipelineExtensions
  {
    public static void Flush(this IPipeWriter writer) => writer.FlushAsync().GetResult();

    public static Task WriteAsync(this IPipeWriter output, byte[] source) => WriteAsync(output, new ReadOnlySpan<byte>(source));

    public static Task WriteAsync(this IPipeWriter output, byte[] source, int index, int count) => WriteAsync(output, new ReadOnlySpan<byte>(source, index, count));

    public static Task WriteAsync(this IPipeWriter output, ArraySegment<byte> source) => WriteAsync(output, (ReadOnlySpan<byte>)source);

    public static Task WriteAsync(this IPipeWriter output, ReadOnlyMemory<byte> source) => WriteAsync(output, source.Span);

    public static Task WriteAsync(this IPipeWriter output, ReadOnlySpan<byte> source)
    {
      var writeBuffer = output.Alloc();
      writeBuffer.Write(source);

      return output.FlushAsyncAwaited();
    }
  }
}
#endif
